<?php
/**
* SocialEngine
*
* @category   Application_Extensions
* @package    Flashgame
* @copyright 2010 YouNet
* @license    http://www.socialengine.net/license/
* @version    $Id: AdminLevelController.php 6755 2010-07-13 22:57:35Z jung $
* @author     Jung
*/

/**
* @category   Application_Extensions
* @package    Flashgame
* @copyright 2010 YouNet
* @license    http://www.socialengine.net/license/
*/
class Flashgame_AdminLevelController extends Core_Controller_Action_Admin
{
    public function indexAction()
    {
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
        ->getNavigation('flashgame_admin_main', array(), 'flashgame_admin_main_level');

        // Get level id
        if( null !== ($id = $this->_getParam('id')) ) {
            $level = Engine_Api::_()->getItem('authorization_level', $id);
        } else {
            $level = Engine_Api::_()->getItemTable('authorization_level')->getDefaultLevel();
        }

        if( !$level instanceof Authorization_Model_Level ) {
            throw new Engine_Exception('missing level');
        }

        $id = $level->level_id;
        // Make form

        $this->view->form = $form = new Flashgame_Form_Admin_Level(array(
      'public' => ( in_array($level->type, array('public')) ),
      'moderator' => ( in_array($level->type, array('admin', 'moderator')) ),
    ));
        $form->level_id->setValue($id);
		$permissionsTable = Engine_Api::_()->getDbtable('permissions', 'authorization');
        $form->populate($permissionsTable->getAllowed('flashgame', $id, array_keys($form->getValues())));
        if(in_array($level->type, array('public')) == 0)
        {
	        // get max allow
	        $mtable  = Engine_Api::_()->getDbtable('permissions', 'authorization');
	        $mselect = $mtable->select()
	        ->where("type = 'flashgame'")
	        ->where("level_id = ?",$id)
	        ->where("name = 'max'");
	        $mallow = $mtable->fetchRow($mselect);
	        if (!empty($mallow))
	            $max = $mallow['value'];
	
	        //$form->max->setValue($max);
	            $max_get = $form->max->getValue();
	            if ($max_get < 1)
	                $form->max->setValue($max);
        }            
        // Check post
        if( !$this->getRequest()->isPost() ) {

            return;
        }

        // Check validitiy
        if( !$form->isValid($this->getRequest()->getPost()) ) {
            return;
        }

        // Process
        $values = $form->getValues();
        
        $db = $permissionsTable->getAdapter();
        $db->beginTransaction();

        try
        {
            // Set permissions
            $permissionsTable->setAllowed('flashgame', $id, $values);
            // Commit
            $db->commit();
        }

        catch( Exception $e )
        {
            $db->rollBack();
            throw $e;
        }

    }

}